package com.dmz.etc.server.netty.client;

import com.dmz.etc.server.config.enums.MsgType;
import com.dmz.etc.server.config.enums.TaskStatus;
import com.dmz.etc.server.domain.ClientTask;
import com.dmz.etc.server.domain.MsgClazz;
import com.dmz.etc.server.service.ClientService;
import com.dmz.etc.server.utils.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


/**
 * @author lee
 */
@Slf4j
public class TaskHandler extends ChannelInboundHandlerAdapter {

    private ClientTask task;

    public TaskHandler(ClientTask clientTask) {
        this.task = clientTask;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("尝试连接到服务:{}", ctx.channel().remoteAddress().toString());
        super.channelActive(ctx);
        ClientService service = SpringUtil.getBean(ClientService.class);
        task.setMsgPhase(MsgType.TYPE_1001);
        MsgClazz m = service.send(task, ctx.channel());
        log.info("客户端发送报文===========================================");
        log.info("报文内容：{}", m.getData());
        ctx.writeAndFlush(m.getData());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("1接收到服务响应===================={task}==================================");
        // 接收服务器的响应消息
        byte[] data = (byte[]) msg;
        log.info("客户端接收到的报文: {}", msg);
        ClientService service = SpringUtil.getBean(ClientService.class);
        MsgClazz msgClazz = service.receive(task, ctx.channel(), data);
        if (msgClazz != null && msgClazz.isToc()) {
            log.info("客户端回复报文===========================================");
            log.info("报文内容：{}", msgClazz.getData());
            ctx.writeAndFlush(msgClazz.getData());
        }else {
            log.info("客户端关闭");
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 处理异常，打印错误信息并关闭连接
        log.error("server client close exception", cause);
        ctx.close();
    }
}